package cn.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;

import cn.pojo.Provider;
import cn.service.ProviderService;
import cn.service.ProviderServiceImp;
import cn.util.Commons;
import cn.util.ExcelUtil;
import cn.util.FileDownload;
import cn.util.Page;

/**
 * Servlet implementation class MainController
 */
@WebServlet("*.ht")
public class ProviderController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Logger log = Logger.getLogger(MainController.class);
	private ProviderService providerService = new ProviderServiceImp();

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		// 获得servlet的请求路径
		String path = request.getServletPath();
		System.out.println("before=" + path);
		path = path.substring(1, path.indexOf("."));
		System.out.println("after=" + path);
		try {
			Class<?> cl = Class.forName("cn.controller.ProviderController");
			Method mt = cl.getDeclaredMethod(path, HttpServletRequest.class, HttpServletResponse.class);
			mt.invoke(this, request, response);
		} catch (Exception e) {
			e.printStackTrace();
			request.getSession().setAttribute("ERROR", "此方法不存在");
			response.sendRedirect("jsp/login.jsp");
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

	// 3、供应商管理
	public void providerList(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1、获得页面提交的用户名
		String proName = request.getParameter("proName");
		proName = proName == null ? "" : proName;
		// 2、获得页码
		String msg = request.getParameter("pageNum");
		Integer pageNum = 1;
		try {
			pageNum = Integer.parseInt(msg);
		} catch (NumberFormatException e) {
			log.debug(e.getMessage());// 捕捉异常
		}
		// 3、构建page对象封装信息
		Page<Provider> page = new Page<Provider>();
		// 4、根据userName获得总条数
		int sum = providerService.totalCount(proName);
		page.init(sum, pageNum);
		// 5、根据用户名进行模糊分页查询
		List<Provider> list = providerService.getProviderLike(proName, page.getRowNum(), Page.pageCount);
		page.setList(list);
		// 6、保存数据到Model中
		request.setAttribute("PAGE", page);
		request.setAttribute("PRONAME", proName);
		// 7、到userList.jsp页面去，展示信息
		request.getRequestDispatcher("/WEB-INF/pages/providerList.jsp").forward(request, response);
	}

	// 4、批量删除
	public void deleteBatch(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String msg = request.getParameter("arr");
		String id[] = {};
		try {
			id = msg.split(",");
		} catch (Exception e) {
			log.debug(e.getMessage());
		}
		Integer[] num = providerService.deleteBatch(id);
		System.out.println("删除了" + num[0] + "条");
		HttpSession session = request.getSession();
		session.setAttribute("DELETENUM", num[0]);
		response.sendRedirect("providerList.ht");
	}

	// 5单个删除
	public void proRemove(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String id = request.getParameter("id");
		int i = providerService.proRemove(id);
		response.sendRedirect("providerList.ht");
	}

	public void toProAdd(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.getRequestDispatcher("/WEB-INF/pages/proAdd.jsp").forward(request, response);
	}

	// proCode:根用户编码获得用户
	public void testProCode(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String proCode = request.getParameter("proCode");
		proCode = proCode == null ? "" : proCode;
		Provider pro = providerService.getProByProCode(proCode);
		Map<String, Boolean> map = new HashMap<String, Boolean>();
		// 被占用了，返回false
		if (pro != null) {
			map.put("result", false);
		} else {
			map.put("result", true);
		}
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		String json = JSON.toJSONString(map);
		out.write(json);
		out.flush();
		out.close();
	}

	public void testPhone(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String proPhone = request.getParameter("proPhone");
		proPhone = proPhone == null ? "" : proPhone;
		Provider pro = providerService.getProByPhone(proPhone);
		Map<String, Boolean> map = new HashMap<String, Boolean>();
		// 被占用了，返回false
		if (pro != null) {
			map.put("result", false);
		} else {
			map.put("result", true);
		}
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		String json = JSON.toJSONString(map);
		out.write(json);
		out.flush();
		out.close();
	}

	public void testProName(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String proName = request.getParameter("proName");
		proName = proName == null ? "" : proName;
		Provider pro = providerService.getProByName(proName);
		Map<String, Boolean> map = new HashMap<String, Boolean>();
		// 被占用了，返回false
		if (pro != null) {
			map.put("result", false);
		} else {
			map.put("result", true);
		}
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		String json = JSON.toJSONString(map);
		out.write(json);
		out.flush();
		out.close();
	}

	public void testProFax(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String proFax = request.getParameter("proFax");
		proFax = proFax == null ? "" : proFax;
		Provider pro = providerService.getProByFax(proFax);
		Map<String, Boolean> map = new HashMap<String, Boolean>();
		System.out.println(pro);
		// 被占用了，返回false
		if (pro != null) {
			map.put("result", false);
		} else {
			map.put("result", true);
		}
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		String json = JSON.toJSONString(map);
		out.write(json);
		out.flush();
		out.close();
	}

	public void toAddPro(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String proCode = request.getParameter("proCode");
		String proFax = request.getParameter("proFax");
		String proDesc = request.getParameter("proDesc");
		String proContact = request.getParameter("proContact");
		String proPhone = request.getParameter("proPhone");
		String proAddress = request.getParameter("proAddress");
		String proName = request.getParameter("proName");
		Provider p = new Provider();
		p.setProAddress(proAddress);
		p.setProCode(proCode);
		p.setProContact(proContact);
		p.setProDesc(proDesc);
		p.setProFax(proFax);
		p.setProName(proName);
		p.setProPhone(proPhone);
		System.out.println(p);
		int i = providerService.toAddPro(p);
		response.sendRedirect("providerList.ht");
	}

	// 6导出excel表格
	public void exportExcel(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String msg = request.getParameter("arr");
		String[] id = {};
		try {
			id = msg.split(",");
		} catch (Exception e) {
			log.debug(e.getMessage());
		}
		List<Provider> list = providerService.getProByid(id);
		// 调用POI
		// request.getServletContext()===appilcation
		String path = request.getServletContext().getRealPath("excel");
		String fileName = Commons.getFileName("pro.xlsx");
		path += File.separator + fileName;// path=D:/tomcat8/java53smsm/excel/sduuyeruser.xlsx
		ExcelUtil.createExcel(Provider.class, list, path);
		// 执行下载操作
		FileDownload.download(request, response, fileName, path);
	}

	public void proView(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String msg = request.getParameter("id");
		String[] id = {};
		try {
			id = msg.split(",");
		} catch (Exception e) {
			log.debug(e.getMessage());
		}
		Provider p = providerService.getProByid(id).get(0);
		request.setAttribute("PRO", p);
		request.getRequestDispatcher("/WEB-INF/pages/proView.jsp").forward(request, response);
	}

	public void toProUpdate(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String id = request.getParameter("id");
		Provider p = providerService.getProById(id);
		request.setAttribute("PRO", p);
		request.getRequestDispatcher("/WEB-INF/pages/proUpdate.jsp").forward(request, response);
	}

	public void proUpdate(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String id = request.getParameter("id");
		Provider p = providerService.getProById(id);
		p.setProAddress(request.getParameter("proAddress"));
		p.setProContact(request.getParameter("proContact"));
		p.setProDesc(request.getParameter("proDesc"));
		p.setProFax(request.getParameter("proFax"));
		p.setProPhone(request.getParameter("proPhone"));
		Integer[] i = providerService.updatePro(p);
		response.sendRedirect("providerList.ht");
	}
}
